package com.jie.algorithm.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.jie.algorithm.R;
import com.jie.algorithm.SettingActivity;
import com.jie.algorithm.algorithm.AlgorithmUtils;
import com.jie.algorithm.common.CodeConstant;
import com.jie.algorithm.common.SpConstant;
import com.jie.algorithm.utils.ColorUtils;
import com.jie.algorithm.utils.ScreenUtils;
import com.jie.commonlib.support.eventbus.Event;
import com.jie.commonlib.support.eventbus.EventBusManager;
import com.jie.commonlib.support.eventbus.EventConstant;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Random;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainFragment extends Fragment {

    private ArrayList<MainBean> mList;
    private MainAdapter mAdapter;
    private int algorithm = SpConstant.DEFAULT_ALGORITHM;
    private int mMaxHeight;
    private int mMaxWidth;

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        EventBusManager.getInstance().register(this);
        return inflater.inflate(R.layout.algo_main_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        View view = getView();
        if (view == null) {
            return;
        }
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        Context context = getContext();
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        mList = new ArrayList<>();
        mAdapter = new MainAdapter(mList);
        recyclerView.setAdapter(mAdapter);

        initMaxSize();
        initData();
    }

    /**
     * 初始化最大宽度和最大高度，用于计算柱状体的宽高
     */
    private void initMaxSize() {
        Context context = getContext();
        int screenHeight = ScreenUtils.getScreenHeight(context);
        int actionBarHeight = ScreenUtils.getActionBarHeight(context);
        int statusBarHeight = ScreenUtils.getStatusBarHeight(context);
        mMaxHeight = screenHeight - actionBarHeight - statusBarHeight;
        mMaxWidth = ScreenUtils.getScreenWidth(context);
    }

    /**
     * 初始化柱状体数据
     */
    private void initData() {
        // 取消上一次的排序任务
        AlgorithmUtils.cancel();
        mList.clear();
        int count = getSpString(SpConstant.SP_KEY_COUNT,SpConstant.DEFAULT_COUNT);
        algorithm = getSpString(SpConstant.SP_KEY_ALGORITHM,SpConstant.DEFAULT_ALGORITHM);
        // 设置算法标题
        getActivity().setTitle(AlgorithmUtils.getAlgorithmName(algorithm));
        // 计算柱状体宽度
        int itemWidth = ((int) (mMaxWidth / count));
        for (int i = 0; i < count; i++) {
            MainBean mainBean = new MainBean();
            mainBean.setWidth(itemWidth);
            // 获取一个随机高度
            int height = new Random().nextInt(mMaxHeight);
            mainBean.setHeight(height);
            float ratio = height * 1.0f / mMaxHeight;
            // 根据高度比例获取一个颜色值
            mainBean.setColor(ColorUtils.calculateColor(ratio));
            mList.add(mainBean);
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 获取存储的值
     * @param key
     * @param defaultValue
     * @return
     */
    private int getSpString(String key,int defaultValue){
        String result = PreferenceManager
                .getDefaultSharedPreferences(getContext())
                .getString(key, String.valueOf(defaultValue));
        return Integer.valueOf(result);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.algo_menu_setting,menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_start){
            AlgorithmUtils.doAlgorithm(mList, algorithm);
            return true;
        }else if (itemId == R.id.menu_reset){
            initData();
            return true;
        }else if (itemId == R.id.menu_set){
            Intent intent = new Intent(getContext(), SettingActivity.class);
            startActivityForResult(intent, CodeConstant.CODE_SETTING);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CodeConstant.CODE_SETTING){
            initData();
        }
    }

    /**
     * 接收到eventbus事件，更新ui
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiverEvent(Event event){
        if (event != null && event.getCode() == EventConstant.CODE_ALGORITHM_OVER){
            if (mAdapter != null){
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBusManager.getInstance().unRegister(this);
        super.onDestroyView();
    }
}
